import React, {useEffect, useState} from "react";
import {Checkbox, List, Modal} from "antd-mobile";

const CheckboxItem = Checkbox.CheckboxItem;

/**
 * 多选-选择器
 * @param data {checked:boolean,label:string,value:string}[] 数据
 * @param visible boolean 是否显示
 * @param setVisible fn 是否显示
 * @param afterClose Fn Modal 完全关闭后的回调
 * @constructor
 */
function ListCheckbox({data,visible,setVisible,afterClose}) {
  const [_data,_setData] = useState(data);
  useEffect(()=>{_setData(data)},[data]);

  const setVal = (idx)=>{
    _data[idx].checked = !data[idx].checked;
    _setData([..._data])
  }
  const _afterClose = (type)=>{
    setVisible(false);
    type === 'ok' && afterClose(_data,_data.filter(v=>v.checked))
  }

  return (
      <Modal visible={visible} popup
             onClose={_afterClose}
             animationType='slide-up'>
        <div className='am-picker-popup-header g-between'>
          <p className='am-picker-popup-item' onClick={_afterClose}>取消</p>
          <p className='am-picker-popup-item am-picker-popup-title'>多选</p>
          <p className='am-picker-popup-item'  onClick={()=>{_afterClose('ok')}}>确定</p>
        </div>
        <List className='v-popup-list'>
          {data.map((v,idx) => (
              <CheckboxItem key={idx}
                            checked={v.checked}
                            onChange={()=>setVal(idx)}>
                {v.label}
              </CheckboxItem>
          ))}
        </List>
      </Modal>
  )

}

export default ListCheckbox;